<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\api\model\hotel\HotelThirdOrder as HotelThirdOrderModel;
use app\api\model\hotel\HotelOrderRefund as HotelOrderRefundModel;

use app\common\controller\Api;

class Hotelorderrefund extends Api
{
    protected $noNeedRight = ['*'];


    //申请售后的展示信息
    public function applydata()
    {
        $order_id = input('order_id',0);

        $order_info = HotelThirdOrderModel::get($order_id);

        if (!$order_info)$this->error('订单不存在');

        $refund_model = new HotelOrderRefundModel();

        $data = [
            'reason'=>$refund_model->reason,
            'pay_money'=>$order_info->pay_money,
            'refund_servicecharge_rate'=>\app\common\model\Config::get(['name'=>'refund_servicecharge_rate'])->value
        ];

        $this->success('',$data);
    }

    //申请售后
    public function apply()
    {
        $order_id = input('order_id',0);
        $reason = input('reason','');
        $images = input('images','');
        $remark = input('remark','');
        $order_model = new HotelThirdOrderModel();
        $order_info = HotelThirdOrderModel::get($order_id);

        if (!$order_info)$this->error('订单不存在');

        $refund_info = HotelOrderRefundModel::get([ 'user_id'=>$this->auth->id,'order_id'=>$order_id]);

        if ($refund_info)$this->error('当前订单已申请售后');

        $refund_model = new HotelOrderRefundModel();

        $refund_servicecharge_rate = \app\common\model\Config::get(['name'=>'refund_servicecharge_rate'])->value/100;

        $realprice = $order_info->pay_money;
        $refundprice = $order_info->pay_money;
        if ($order_info->pay_time+1800<time()){
            $service_charge = bcmul($realprice,$refund_servicecharge_rate,2);
            $refundprice = bcsub($realprice,$service_charge,2);
        }
        $data = [
            'user_id'=>$this->auth->id,
            'hotel_id'=>$order_info['hotel_id'],
            'order_id'=>$order_id,
            'reason'=>$reason,
            'remark'=>$remark,
            'images'=>$images,
            'realprice'=>$realprice,
            'refundprice'=>$refundprice
        ];

        $res = $refund_model->save($data);
        if ($res){
            $order_model->orderRefund($order_id);
        }
        $this->success('',$res);
    }


    //取消售后
    public function cancel()
    {
        $order_id = input('order_id',0);

        $refund_info = HotelOrderRefundModel::get([ 'user_id'=>$this->auth->id,'order_id'=>$order_id]);

        if (!$refund_info)$this->error('当前订单未申请售后');
        $refund_info->status = 3;
        $res = $refund_info->save();

        if ($res){
            $order_model = new HotelThirdOrderModel();
            $order_model->orderCancelRefund($order_id);
        }
        $this->success('',$res);
    }
}